function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的request
 */
function request(url, data = {}, method = "GET",
  header = { 'content-type': 'application/x-www-form-urlencoded' }) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: header,
      success: function (res) {
        console.log("success");
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {
          reject(res.errMsg);
        }
      },
      fail: function (err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

/**
 * 封封微信的uploadFile
 */
function uploadFile(url, path, data = {}, name = "image", method = "POST",
  header = { 'content-type': 'application/x-www-form-urlencoded' }) {
  return new Promise(function (resolve, reject) {
    wx.uploadFile({
      url: url,
      filePath: path,
      formData: data,
      name: name,
      method: method,
      header: header,
      success: function (res) {
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {
          reject(res.errMsg);
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          console.log(res)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

/**
 * 获取微信用户信息
 */
function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        console.log(res)
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}

/**
 * 错误提示
 */
function errorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/cha.png'
  })
}

/**
 * 成功提示
 */
function successToast(msg) {
  wx.showToast({
    title: msg,
    icon: 'success'
  })
}

module.exports = {
  formatTime,
  request,
  uploadFile,
  checkSession,
  login,
  getUserInfo,
  errorToast,
  successToast
}